<template>
  <div class="nav-item">
    <!-- No children - simple menu item -->
    <el-menu-item
      :index="resolvePath(basePath)"
      v-if="!hasChildren"
      class="nav-item__menu-item"
    >
      <i v-if="item.icon" :class="item.icon"></i>
      <span slot="title">{{ item.name }}</span>
    </el-menu-item>

    <!-- With children - submenu -->
    <el-submenu v-else :index="resolvePath(basePath)" class="nav-item__submenu">
      <template slot="title">
        <i v-if="item.icon" :class="item.icon"></i>
        <span>{{ item.name }}</span>
      </template>
      <NavItem
        v-for="child in item.child"
        :key="resolvePath(child.url)"
        :item="child"
        :basePath="resolvePath(child.url)"
      />
    </el-submenu>
  </div>
</template>

<script>
export default {
  name: "NavItem",
  props: {
    item: {
      type: Object,
      required: true,
      validator: (item) => {
        return item.name && item.url;
      },
    },
    basePath: {
      type: String,
      required: true,
    },
  },
  computed: {
    hasChildren() {
      return this.item.child && this.item.child.length > 0;
    },
  },
  methods: {
    resolvePath(relativePath) {
      return relativePath.startsWith("/")
        ? relativePath //绝对路径
        : `${this.basePath}/${relativePath}`; //相对路径，括号里如果是非/拼接为绝对路径
    },
  },
};
</script>

<style scoped lang="scss">
.nav-item {
  &__menu-item,
  &__submenu {
    i {
      margin-right: 10px;
      color: inherit;
    }

    span {
      vertical-align: middle;
    }
  }

  /* Adjust nested menu items */
  ::v-deep .el-menu--inline {
    &:hover {
      background-color: rgba(255, 255, 255, 0.1) !important;
    }
  }
}
</style>
